extends "res://scenes/base_scene.gd"
signal destory_player(id : int)

@onready var query_timer: Timer = $QueryTimer
@onready var player_group: Node2D = $PlayerGroup

const BASE_ACTOR = preload("uid://tawrpfun071p")

var player_like_data : Dictionary = {}

func _ready() -> void:
	super._ready()
	_init_signal()
	await get_tree().create_timer(1.0).timeout
	call_deferred("_init_server_player_data")

func _init_signal() -> void :
	multiplayer.auth_timeout = 2.0
	if multiplayer.is_server() :
		SceneManage._on_peer_disconnected.connect(_remove_player)
		SceneManage._on_peer_connected.connect(_create_player)
		multiplayer.auth_callback = _on_auth_callback
	else :
		multiplayer.auth_callback = func call_able():pass
		multiplayer.peer_authenticating.connect(_on_peer_authenticating)
		multiplayer.peer_authentication_failed.connect(_on_peer_authentication_failed)

func _remove_player(id : int) -> void :
	if not multiplayer.is_server() : return
	destory_player.emit(str(id))

func _create_player(id : int) -> void :
	print(multiplayer.get_unique_id(),"连接成功")
	var player = BASE_ACTOR.instantiate()
	player.player_data = player_like_data.get(id)
	player.name = str(id)
	destory_player.connect(player._on_destory_event)
	player_group.call_deferred("add_child",player)

func _init_server_player_data() -> void :
	var game_data = Global.current_game_data
	var player_data = await SceneManage._get_game_data(game_data.game_id,"player_data")
	Global.current_player_data = PlayerData.new(player_data) if player_data else PlayerData.new()
	call_deferred("_create_player",multiplayer.get_unique_id())

func _on_auth_callback(id: int, data: PackedByteArray) :
	if data.size() < 1 : return
	var request_data = JSON.parse_string(data.get_string_from_utf8())
	print(multiplayer.get_unique_id(),"鉴权数据：",request_data)
	if not request_data : return
	#var game_name = request_data.game_name
	#var game_id = request_data.game_id
	#var user_id = request_data.user_id
	var game_auth = request_data.get("game_auth","")
	if Global.current_game_auth.length() > 0 :
		if not is_same(game_auth,Global.current_game_auth) :
			return
	multiplayer.complete_auth(id)

func _on_peer_authenticating(id: int) -> void :
	print(multiplayer.get_unique_id(),"申请鉴权")
	var game_data = Global.current_game_data._get_stuct()
	game_data.set("game_auth",Global.current_game_auth)
	var player_data = await SceneManage._get_game_data(game_data.game_id,"player_data")
	Global.current_player_data = PlayerData.new(player_data) if player_data else PlayerData.new()
	multiplayer.send_auth(id,JSON.stringify(game_data).to_utf8_buffer())
	multiplayer.complete_auth(id)

func _on_peer_authentication_failed(_id: int) -> void :
	print("加入房间失败！")
	get_tree().call_deferred("change_scene_to_file","res://scenes/main.tscn")
